package org.example.service;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.example.entity.Account;
import org.example.entity.Admin;
import org.example.entity.Admin;
import org.example.exception.CustomException;
import org.example.mapper.AdminMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    public List<Admin> selectAll(Admin admin) {
        List<Admin> list= adminMapper.selectAll(admin);
        return list;
    }

    public Admin selectById(Integer id) {
       Admin admin= adminMapper.selectById(id);
       return admin;
    }

    public PageInfo<Admin> selectPage(Admin admin, @RequestParam(defaultValue = "1") Integer pageNum, Integer pageSize){
        PageHelper.startPage(pageNum,pageSize);
        List<Admin> list=adminMapper.selectAll(admin);
        return PageInfo.of(list);
    }
    public void add(Admin admin) {
        String username = admin.getUsername();
        Admin dbAdmin= adminMapper.selectByUsername(username);
        if(dbAdmin != null) {//账号已存在
            throw new CustomException("500","账号已存在");
        }
        if(StrUtil.isBlank(admin.getPassword())){//密码没填
            admin.setPassword("admin");//默认密码
        }
        if(StrUtil.isBlank(admin.getName())){//名字没填
             admin.setName(admin.getUsername());//默认名称
        }
        admin.setRole("ADMIN");//员工角色
        adminMapper.insert(admin);

    }

    public void delete(Integer id) {

        adminMapper.delete(id);
    }

    public void upadte(Admin admin) {
        adminMapper.update(admin);
    }

    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            this.delete(id);
        }
    }
    public Admin login(Account account) {
        String username = account.getUsername();
        Admin dbAdmin= adminMapper.selectByUsername(username);
        if(dbAdmin == null) {
            throw new CustomException("500", "账号不存在");
        }
        String password = account.getPassword();

        if(!dbAdmin.getPassword().equals(password)) {
            throw new CustomException("500","密码错误");
        }

        return dbAdmin;
    }

    public void updatePassword(Account account) {
        Integer id = account.getId();
        Admin dbAdmin= adminMapper.selectById(id);
        if(!dbAdmin.getPassword().equals(account.getPassword())) {
            throw new CustomException("500","原密码错误");
        }
        dbAdmin.setPassword(account.getNewPassword());
        adminMapper.update(dbAdmin);
    }
}
